package com.jiang.realm;


import com.jiang.bean.User;
import com.jiang.mapper.UserMapper;
import com.jiang.utils.DebugUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 18/3/7.
 */
@Slf4j
public class MyPerRealm extends AuthorizingRealm {
    @Resource
    private UserMapper userMapper;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    public String getName() {
        return "MyPerRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DebugUtil.sout("授权开始");
        //***************查询用户角色开始**********
        List list = principalCollection.asList();
        System.out.println(list);
        User user = (User) list.get(0);
        Integer roleid = user.getRoleid();
        String role = userMapper.selectRoleByRoleId(roleid);
        DebugUtil.sout("用户权限：" + role);
        //***************查询用户角色结束**********
        //授权信息对象，用来保存所有角色和授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(role);
//        info.addStringPermission("123");

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        log.info("登录开始,用户名{}",username);

        User user = userMapper.selectUserByLogname(username);
        if (user == null) {
            throw new UnknownAccountException("账号异常/不存在");
        }
//        String salt = user.getSalt();
//        String pwdInDatabase = user.getLoginpwd();
//        String pwd = SaltUtil.addsalt(password,salt);

        //获取token中的密码并比较是否与数据库中一致
//        if (!pwdInDatabase.equals(pwd)) {
        if (!password.equals(user.getLoginpwd())) {
            throw new IncorrectCredentialsException("密码错误");
        }
        return new SimpleAuthenticationInfo(user, password, getName());
    }
    private String  salltUtil(String pwd,String salt){
        String result = new Md5Hash(pwd,salt).toString();
        return result;
    }
}
